<?php

namespace Addons\OaSystem\Controller;
use Think\ManageBaseController;

class OaApplyItemController extends OaBaseController
{
    var $model;
    var $teacherLvls;

    function _initialize()
    {
        $this->model = $this->getModel('oa_apply_item');
        $this->teacherLvls = array('副高', '正高', '院士专家');

        parent::_initialize();
        $controller = strtolower(CONTROLLER_NAME);

        $res ['title'] = '报销审批-明细条目添加';
        $res ['url'] = addons_url('OaSystem://OaApplication/lists', array('mdm' => I('mdm')));
        $res ['class'] = $controller == 'OaApplication' ? 'current' : '';
        $nav [] = $res;
        $this->assign('nav', $nav);
    }

    function add(){
        if(IS_POST) {
            $data['application_id'] = $_POST['application_id'];
            $data['type'] = $_POST['type'];
            $data['description'] = $_POST['description'];
            $data['total'] = floatval($_POST['total']);
            $pictureIds = $_POST['pictures'];

            if(($application = $this->getApplication($data['application_id'])) == false)
                return false;

            if($_POST['button_cancel']==1) {
                $url = addons_url('OaSystem://OaApplication/add', array('mdm' => I('mdm'), 'type'=>$application['type'], 'subtype'=>$application['subtype'], 'application_id'=>$data['application_id']));
                redirect($url);
            }

            if($data['total'] == 0) {
                $this->error('金额数输入错误，请检查!');
                return false;
            }

            if($application['subtype'] == 0) {
                $data['itinerary_id'] = $_POST['itinerary_id'];
            }
            if($application['subtype']==1 && $data['type']=='授课费') {
                if(empty($_POST['hours']) || empty($_POST['teacherLvl'])) {
                    $this->error('请输入课时或者老师职称!');
                    return false;
                }
                $content['trainingHours'] = $_POST['hours'];
                $content['trainerLevel'] = $_POST['teacherLvl']-1;
                $content['trainerLevels'] = $this->teacherLvls;
            }
            $content['invoiceCount'] = $_POST['invoiceCount'];
            if(!empty($_POST['dailyStandard'])) {
                $tmp = json_decode($_POST['dailyStandard'], true);
                $content['standard'] = $tmp['des'];
                $content['standard_val'] = $tmp['val'];
            }
            if(!empty($_POST['quantity'])) $content['qty'] = $_POST['quantity'];
            if(!empty($_POST['price'])) $content['price'] = floatval($_POST['price']);
            if(!empty($_POST['fileCount'])) $content['fileCount'] = $_POST['fileCount'];
            if(!empty($_POST['fileids'])) {
                $files = json_decode($_POST['fileids'], true);
                if(count($files) != $content['fileCount']) {
                    $this->error('请检查附件数量是否输入正确!');
                    return false;
                }
                for ($i = 0; $i < count($files); $i++){
                    $tmp = M('File')->where(array('id'=>$files[$i]['id']))->find();
                    $files[$i]['url'] = "/Uploads/Download/".$tmp['savepath'].$tmp['savename'];
                }
                $content['files'] = json_encode($files);
                $content['fileids'] = $_POST['fileids'];
            }
            $data['content'] = json_encode($content, JSON_UNESCAPED_UNICODE);

//            if($application['subtype'] == 0) {
//                $apply_content = json_decode($application['content'], true);
//                $itinerary_id = empty($apply_content['itinerary']) ? 0 : (end($apply_content['itinerary'])['id']+1);
//                $itinerary = array(
//                    'id' => $itinerary_id,
//                    'itemType' => $apply_content['itemType'],
//                    'start' => $_POST['start_date'],
//                    'end' => $_POST['end_date'],
//                    'src' => explode('-', $_POST['start_addr']),
//                    'dst' => explode('-', $_POST['end_addr']),
//                    'days' => $this->getDays($_POST['start_date'], $_POST['end_date'], $itinerary_id)
//                );
//
//                if($this->checkItinerary($apply_content['itinerary'], $_POST) == false) {
//                    return false;
//                }
//            }

            $pictures = array();
            foreach ($pictureIds as $picId) {
                $picUrl = strstr(get_picture_url($picId), "/Uploads");
                array_push($pictures, $picUrl);
            }
            $data['pictures'] = json_encode($pictures);

            if(M('oa_apply_item')->add($data) == false) {
                $this->error('添加 审批条目 数据库出错！');
                return false;
            } else {
                $url = addons_url('OaSystem://OaApplication/add', array('mdm' => I('mdm'), 'type'=>$application['type'], 'subtype'=>$application['subtype'], 'application_id'=>$data['application_id']));
                $this->success ( '创建' . $model ['title'] . '成功！', $url);
            }
        } else {
            $application_id = $_GET['application_id'];
            $itinerary_id = $_GET['itinerary_id'];
            if(($apply = $this->getApplication($application_id)) == false)
                return false;

            $content = json_decode($apply['content'], true);
            $itemType = $content['itemTypes'][$content['itemType']];

            if($apply['subtype'] == 0) {
                $std_res = $this->calReimburseAmountByStandard($content['itinerary'][$itinerary_id]);
                $itemInfo['standard_hint'] = $this->buildTripStdHintStr($std_res, $itemType);
                $itemInfo['dailyStandard'] = $this->getItemDailyStandard($std_res, $itemType);
                if($itemType == '市内交通费' || $itemType == '伙食补助费') {
                    $itemInfo['isQuotaReimbursement'] = 1;
                    $itemInfo['total'] = ($itemType == '市内交通费') ? $std_res['traffic_sum'] : $std_res['meals_sum'];
                }
            }
            if($apply['subtype'] == 1 && $itemType == '授课费') {
                $meeting_std = db_find('oa_meeting_reimburse_standard');
                $itemInfo['tuition_std'] = $meeting_std['tuition'];
                $trainerLevels[0]['id'] = '';
                $trainerLevels[0]['name'] = '';
                $trainerLevels[0]['selected'] = 'disabled selected';
                foreach ($this->teacherLvls as $i => $v) {
                    $trainerLevels[$i+1]['id'] = $i + 1;
                    $trainerLevels[$i+1]['name'] = $v;
                }
                $trainerLevels[$item_content['trainerLevel']]['selected'] = 'selected';
                $itemInfo['trainerLevels'] = $trainerLevels;
            }

            $itemInfo['reimburse_type'] = $apply['subtype'];
            $itemInfo['type'] = $itemType;
            $itemInfo['application_id'] = $application_id;
            $itemInfo['itinerary_id'] = $itinerary_id;
            $itemInfo['start_date'] = date('Y-m-d',NOW_TIME);
            $itemInfo['end_date'] = date('Y-m-d',NOW_TIME);
            $itemInfo['start_addr'] = '西藏自治区-拉萨市-城关区';
            $itemInfo['end_addr'] = '西藏自治区-拉萨市-城关区';

            $this->assign('itemInfo', $itemInfo);
            $this->display();
        }
    }



    function edit(){
        if(IS_POST) {
            $data['id'] = $_POST['id'];
            $data['application_id'] = $_POST['application_id'];
            $data['type'] = $_POST['type'];
            $data['description'] = $_POST['description'];
            $data['total'] = floatval($_POST['total']);
            $pictureIds = $_POST['pictures'];

            if(($application = $this->getApplication($data['application_id'])) == false)
                return false;

            if($_POST['button_cancel']==1) {
                $url = addons_url('OaSystem://OaApplication/add', array('mdm' => I('mdm'), 'type'=>$application['type'], 'subtype'=>$application['subtype'], 'application_id'=>$data['application_id']));
                redirect($url);
            }

            if($data['total'] == 0) {
                $this->error('金额数输入错误，请检查!');
                return false;
            }

            if($application['subtype']==1 && $data['type']=='授课费') {
                if(empty($_POST['hours']) || empty($_POST['teacherLvl'])) {
                    $this->error('请输入课时或者老师职称!');
                    return false;
                }
                $content['trainingHours'] = $_POST['hours'];
                $content['trainerLevel'] = $_POST['teacherLvl']-1;
                $content['trainerLevels'] = $this->teacherLvls;
            }
            $content['invoiceCount'] = $_POST['invoiceCount'];
            if(!empty($_POST['dailyStandard'])) {
                $tmp = json_decode($_POST['dailyStandard'], true);
                $content['standard'] = $tmp['des'];
                $content['standard_val'] = $tmp['val'];
            }
            if(!empty($_POST['quantity'])) $content['qty'] = $_POST['quantity'];
            if(!empty($_POST['price'])) $content['price'] = floatval($_POST['price']);
            if(!empty($_POST['fileCount'])) $content['fileCount'] = $_POST['fileCount'];
            if(!empty($_POST['fileids'])) {
                $files = json_decode($_POST['fileids'], true);
                if(count($files) != $content['fileCount']) {
                    $this->error('请检查附件数量是否输入正确!');
                    return false;
                }
                for ($i = 0; $i < count($files); $i++){
                    $tmp = M('File')->where(array('id'=>$files[$i]['id']))->find();
                    $files[$i]['url'] = "/Uploads/Download/".$tmp['savepath'].$tmp['savename'];
                }
                $content['files'] = json_encode($files);
                $content['fileids'] = $_POST['fileids'];
            }
            $data['content'] = json_encode($content, JSON_UNESCAPED_UNICODE);

            if(($item = $this->getApplicationItem($_POST['id'])) == false)
                return false;

            $oldPictures = json_decode($item['pictures'], true);
            $newPictures = array();
            foreach ($pictureIds as $picId) {
                if($picId < count($oldPictures))
                    $picUrl = $oldPictures[$picId];
                else
                    $picUrl = strstr(get_picture_url($picId), "/Uploads");
                array_push($newPictures, $picUrl);
            }
            $data['pictures'] = json_encode($newPictures);

            if(db_save('oa_apply_item', ['id'=>$data['id'], 'application_id'=>$data['application_id']], $data) === false) {
                $this->error(__METHOD__.'['.__LINE__.']'.'保存 申请明细表 错误！');
                return false;
            } else {
                $url = addons_url('OaSystem://OaApplication/add', array('mdm' => I('mdm'), 'type'=>$application['type'], 'subtype'=>$application['subtype'], 'application_id'=>$data['application_id']));
                $this->success ( '修改' . $model ['title'] . '成功！', $url);
            }
        } else {
            $application_id = $_GET['application_id'];
            $item_id = $_GET['item_id'];

            if(($apply = $this->getApplication($application_id)) == false)
                return false;
            if(($item = $this->getApplicationItem($item_id)) == false)
                return false;
            if($item['application_id'] != $application_id) {
                $this->error(__METHOD__.'['.__LINE__.']'.'传入的明细表ID不属于改申请表！');
                return false;
            }

            $content = json_decode($apply['content'], true);
            $item_content = json_decode($item['content'], true);
            $invoiceCount = (empty($item_content['invoiceCount'])) ? 0 : $item_content['invoiceCount'];
            $item['invoiceCount'] = $invoiceCount;
            $item['quantity'] = $item_content['qty'];
            $item['price'] = $item_content['price'];
            $item['fileCount'] = $item_content['fileCount'];
            $item['fileids'] = $item_content['fileids'];

            if($apply['subtype'] == 0) {
                $std_res = $this->calReimburseAmountByStandard($content['itinerary'][$item['itinerary_id']]);
                $item['standard_hint'] = $this->buildTripStdHintStr($std_res, $item['type']);
                $item['dailyStandard'] = $this->getItemDailyStandard($std_res, $item['type']);
                if($item['type'] == '市内交通费' || $item['type'] == '伙食补助费') {
                    $item['isQuotaReimbursement'] = 1;
                }
            }
            if($apply['subtype'] == 1 && $item['type'] == '授课费') {
                $meeting_std = db_find('oa_meeting_reimburse_standard');
                $item['tuition_std'] = $meeting_std['tuition'];

                $item['hours'] = $item_content['trainingHours'];
                $trainerLevels = array();
                foreach ($item_content['trainerLevels'] as $i => $v) {
                    $trainerLevels[$i]['id'] = $i + 1;
                    $trainerLevels[$i]['name'] = $v;
                }
                $trainerLevels[$item_content['trainerLevel']]['selected'] = 'selected';
                $item['trainerLevels'] = $trainerLevels;
            }
            if($apply['subtype'] == 1 && $item['type'] == '其他费用') {
                $item['isMeetingReimbursementOther'] = 1;
            }
            if($apply['subtype'] == 2) {
                $item['isOtherReimbursement'] = 1;
            }

            $itemPictures_url = json_decode($item['pictures'], true);
            foreach($itemPictures_url as $j => $picUrl) {
                $itemPictures[$j]['id'] = $j;
                $itemPictures[$j]['url'] = SITE_URL.$picUrl;
            }
            $item['pictures'] =  $itemPictures;

            $this->assign('data', $item);
            $res ['title'] = '报销审批-明细条目修改';
            $nav [] = $res;
            $this->assign('nav', $nav);
            $this->display();
        }

    }

    function del()
    {
        $application_id = $_GET['application_id'];
        $item_id = $_GET['item_id'];

        if(($application = $this->getApplication($application_id)) == false)
            return false;

        if(M('oa_apply_item')->where(['id'=>$item_id, 'application_id'=>$application_id])->delete() == false) {
            $this->error('删除 审批明细条目 数据库出错！');
            return false;
        } else {
            $url = addons_url('OaSystem://OaApplication/add', array('mdm' => I('mdm'), 'type'=>$application['type'], 'subtype'=>$application['subtype'], 'application_id'=>$application_id));
            $this->success ( '删除' . $model ['title'] . '成功！', $url);
        }
    }

    private function getApplicationItem($id) {
        if(empty($id)){
            $this->error(__METHOD__.'['.__LINE__.']'.'传入 申请明细表 ID 为空！');
            return false;
        }

        if(($data =db_find('oa_apply_item', ['id'=>$id]))== NULL) {
            $this->error(__METHOD__.'['.__LINE__.']'.'找不到对应的的申请明细表！');
            return false;
        }
        return $data;
    }

    private function getApplication($id) {
        if(empty($id)){
            $this->error(__METHOD__.'['.__LINE__.']'.'传入 申请表 ID 为空！');
            return false;
        }

        if(($data =db_find('OaApplication', ['id'=>$id]))== NULL) {
            $this->error(__METHOD__.'['.__LINE__.']'.'找不到对应的的申请表！');
            return false;
        }
        return $data;
    }

    private function calReimburseAmountByStandard($content) {
        if(empty($content['start']) || empty($content['end']) || empty($content['dst']) || empty($content['days']) || empty($content['people_num'])) {
            $this->error(__METHOD__.'['.__LINE__.']'.'传入的 时间 地点 人数 有空的参数！');
            return false;
        }

        if(($standard = $this->findReimburseStandardTable($content['dst'])) == false)
            return false;

        $userInfo = $this->getCurUserInfo();
        $standard['normal'] = json_decode($standard['normal'], true)[$userInfo['admin_level']];
        $standard['high'] = json_decode($standard['high'], true)[$userInfo['admin_level']];
        $standard['high_time'] = json_decode($standard['high_time'], true);

        $tripDays = $this->calculateTripDays($content['start'], $content['end'], $standard['high_time']);

        $std_res = $standard;
        $std_res['hotel'] = $standard['normal']*$tripDays['hotel_normal'] + $standard['high']*$tripDays['hotel_high'];
        $std_res['meals_sum'] = $standard['meals']*$content['days']*$content['people_num'];
        $std_res['traffic_sum'] = $standard['traffic']*$content['days']*$content['people_num'];
        $std_res['total_days'] = $content['days'];
        $std_res['hotel_high_days'] = $tripDays['hotel_high'];
        $std_res['hotel_normal_days'] = $tripDays['hotel_normal'];
        $std_res['city'] = $content['dst'][1];
        $std_res['people_num'] = $content['people_num'];

        return $std_res;
    }

    private function findReimburseStandardTable($addr) {
        $municipality = array('北京', '上海', '天津', '重庆');

        $province = $addr[0];
        $tmp = substr($province, 0, 6);
        $map['province'] = array('like', $tmp.'%');
        $city = in_array($province, $municipality) ? $addr[2] : $addr[1];
        $tmp = substr($city, 0, 6);
        $map['city'] = array('like', $tmp.'%');
        if(($standard = db_find('oa_reimbursement_standard', $map)) == NULL) {
            $map['city'] = '其它';
            if(($standard = db_find('oa_reimbursement_standard', $map)) == NULL) {
                $this->error(__METHOD__ . '[' . __LINE__ . ']' . '根据地址[省-市]找不到对应的报销标准表！');
                return false;
            }
        }

        return $standard;
    }

    private function calculateTripDays($start_date, $end_date, $high_season) {
        $start_time = strtotime($start_date);
        $end_time = strtotime($end_date);
        $start_year = explode('-', $start_date)[0];
        $end_year = explode('-', $end_date)[0];
        $day_time = 86400;

        $tripDays['hotel_total'] =  round(($end_time-$start_time)/$day_time);
        $tripDays['hotel_high'] = 0;
        if(empty($high_season)) {
            $tripDays['hotel_normal'] = $tripDays['hotel_total'];
            $tripDays['total'] = $tripDays['hotel_total'] + 1;
            return $tripDays;
        }

        $hs_times = 0;
        foreach ($high_season as $hs) {
            $hs_start = strtotime($start_year.'-'.str_replace('.', '-', strstr($hs, '-', true)));
            $hs_end = strtotime($start_year.str_replace('.', '-', strstr($hs, '-', false)));
            if($hs_end < $hs_start) {
                $hs_end = strtotime(($start_year+1).str_replace('.', '-', strstr($hs, '-', false)));
            }
            for($t = $start_time; $t <= $end_time; $t++) {
                if($hs_start <= $t && $t <= ($hs_end+$day_time))
                    $hs_times++;
            }

            if($end_year > $start_year) {
                $hs_start = strtotime($end_year.'-'.str_replace('.', '-', strstr($hs, '-', true)));
                $hs_end = strtotime($end_year.str_replace('.', '-', strstr($hs, '-', false)));
                if($hs_end < $hs_start) {
                    $hs_end = strtotime(($end_year+1).str_replace('.', '-', strstr($hs, '-', false)));
                }
                for($t = $start_time; $t <= $end_time; $t++) {
                    if($hs_start <= $t && $t <= ($hs_end+$day_time))
                        $hs_times++;
                }
            }
        }

        $tripDays['hotel_high'] =  round($hs_times/$day_time);
        $tripDays['hotel_normal'] = $tripDays['hotel_total'] - $tripDays['hotel_high'];
        if($end_time == $start_time) {
            $tripDays['hotel_total'] = 1;
            if($hs_times > ($day_time/2))
                $tripDays['hotel_high'] = 1;
            else
                $tripDays['hotel_normal'] = 1;
        }
        $tripDays['total'] = $tripDays['hotel_total'] + 1;
        return $tripDays;
    }

    private function buildTripStdHintStr($std_res, $itemType) {
        // var_dump($std_res);
        if($itemType == '住宿费') {
            $hs = (empty($std_res['high']) || empty($std_res['high_time'])) ? false : true;
            $standard_hint = '[提示: '.$std_res['province'].'-'.$std_res['city'].' 您的'.($hs?'平时':'').'报销标准是'.$std_res['normal'].'元/天, ';
            $standard_hint .= $hs?('旺季('.implode(',', $std_res['high_time']).')报销标准是'.$std_res['high'].'元/天, '):'';
            $standard_hint .= '按当前日期选择'.($hs?'平时':'').'是'.$std_res['hotel_normal_days'].'天, ';
            $standard_hint .= $hs?('旺季是'.$std_res['hotel_high_days'].'天, '):'';
            $standard_hint .= '合计总额度不应该超过 '.'<font style="font-weight:bold">'.$std_res['hotel'].'</font>'.' 元]';
        } else if($itemType == '市内交通费') {
            $standard_hint = '[提示: '.$std_res['province'].'-'.$std_res['city'].' 您的交通补助标准是'.$std_res['traffic'].'元/天, ';
            $standard_hint .= '按当前日期选择总共是'.$std_res['total_days'].'天, 人数为'.$std_res['people_num'].', ';
            $standard_hint .= '合计总额为 '.'<font style="font-weight:bold">'.$std_res['traffic_sum'].'</font>'.' 元]';
        } else if($itemType == '伙食补助费') {
            $standard_hint = '[提示: '.$std_res['province'].'-'.$std_res['city'].' 您的伙食补助标准是'.$std_res['meals'].'元/天, ';
            $standard_hint .= '按当前日期选择总共是'.$std_res['total_days'].'天, 人数为'.$std_res['people_num'].', ';;
            $standard_hint .= '合计总额为 '.'<font style="font-weight:bold">'.$std_res['meals_sum'].'</font>'.' 元]';
        }
        return $standard_hint;
    }

    private function getItemDailyStandard($std_res, $itemType) {
        $standard = array();
        if($itemType == '住宿费') {
            $hs = (empty($std_res['high']) || empty($std_res['high_time'])) ? false : true;
            if($hs) {
                $standard['des'] = '淡季&nbsp'.$std_res['normal'].'&nbsp元/人天,&nbsp旺季('.implode(',', $std_res['high_time']).')&nbsp'.$std_res['high'].'&nbsp元/人天';
                $standard['val'] = $std_res['high'];
            }
            else {
                $standard['des'] = $std_res['normal'].'&nbsp元/人天';
                $standard['val'] = $std_res['normal'];
            }
        } else if($itemType == '市内交通费') {
            $standard['des'] = $std_res['traffic'].'&nbsp元/人天';
            $standard['val'] = $std_res['traffic'];
        } else if($itemType == '伙食补助费') {
            $standard['des'] = $std_res['meals'].'&nbsp元/人天';
            $standard['val'] = $std_res['meals'];
        } else {
            $standard['des'] = null;
        }
        return json_encode($standard, JSON_UNESCAPED_UNICODE);
    }
}

